package com.cxq;

import java.util.concurrent.CountDownLatch;

/**
 * Created by cxq on 2020/7/26.
 */
public class CoachRace {

    //设置要等待的运动员是3个
    private CountDownLatch countDownLatch = new CountDownLatch(3);


    //运动员方法，由运动员线程调用
    public void racer(){

        //获取运动员名称
        String name = Thread.currentThread().getName();
        //运动员开始准备，打印准备信息
        System.out.println(name+"准备中。。。");
        //线程睡眠1000毫秒，表示运动员准备完毕
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //运动员准备完毕，打印准备完毕信息
        System.out.println(name+"准备完毕！");
        countDownLatch.countDown();
    }


    //教练员方法，由教练调用
    public void coach(){
        //获取教练员名称
        String name = Thread.currentThread().getName();
        //教练员等待所有运动员准备完毕，打印等待信息
        System.out.println(name+"等待运动员。。。。");
        //调用countDownLatch的await方法等待其他线程准备完毕
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //所有运动员已经就绪，教练开始训练，打印训练信息
        System.out.println("所有运动员已就绪，"+name+"开始执行训练！");
    }

    public static void main(String[] args) {
        //创建实例
        final CoachRace coachRace = new CoachRace();
        //创建三个运动员，调用racer方法
        Thread racer1 = new Thread(()->coachRace.racer(),"运动员1");
        Thread racer2 = new Thread(()->coachRace.racer(),"运动员2");
        Thread racer3 = new Thread(()->coachRace.racer(),"运动员3");
        //创建一个线程对象，调用coach方法
        Thread coach = new Thread(()->coachRace.coach(),"教练员");
        //教练员准备
        coach.start();
        //运动员准备
        racer1.start();
        racer2.start();
        racer3.start();
    }

}
